<?php

function unzip($file_name, $option = true /* option = false -> unzip here else unzip to folder */) {
  $zip = zip_open($file_name);
  if ($zip) {
    $path = dirname($file_name) . '/';
    if ($option == true) {
      if (!file_exists($path . pathinfo($file_name, PATHINFO_FILENAME))) {
        mkdir($path . pathinfo($file_name, PATHINFO_FILENAME), 0777);
      }
      $path .= pathinfo($file_name, PATHINFO_FILENAME) . '/';
    }
    while ($zip_entry = zip_read($zip)) {
      $name = zip_entry_name($zip_entry);
      if (strpos($name, '.') !== false) {
        $f = fopen($path . zip_entry_name($zip_entry), 'w+');
        if (zip_entry_open($zip, $zip_entry, "r")) {
          $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
          fwrite($f, $buf);
          zip_entry_close($zip_entry);
        }
        fclose($f);
      } else {
        if (!file_exists($path . $name)) {
          mkdir($path . $name, 0777);
        }
      }
    }
    zip_close($zip);
  }
}

function read_file_as_string($filename) {
  try {
    $out = '';
    $lines = file($filename);
    foreach ($lines as $line) {
      $out .= $line;
    }
    return $out;
  } catch (Exception $ex) {
    return '';
  }
}

function copydir($source, $target) {
  if (is_dir($source)) {
    @mkdir($target, 0777);
    $d = dir($source);
    while (FALSE !== ( $entry = $d->read() )) {
      if ($entry == '.' || $entry == '..') {
        continue;
      }
      $Entry = $source . '/' . $entry;
      if (is_dir($Entry)) {
        copydir($Entry, $target . '/' . $entry);
        continue;
      }
      copy($Entry, $target . '/' . $entry);
    }
    $d->close();
  } else {
    copy($source, $target);
  }
}

function deletedir($dirname, $delete_it = true) {
  if (is_dir($dirname))
    $dir_handle = opendir($dirname);
  if (empty($dir_handle))
    return false;
  while ($file = readdir($dir_handle)) {
    if ($file != "." && $file != "..") {
      if (!is_dir($dirname . "/" . $file))
        @unlink($dirname . "/" . $file);
      else
        deletedir($dirname . '/' . $file);
    }
  }
  closedir($dir_handle);
  if ($delete_it) {
    @rmdir($dirname);
  }
  return true;
}

function movedir($source, $target) {
  copydir($source, $target);
  deletedir($source);
}

function addDir(&$zip, $path) {
  $zip->addEmptyDir($path);
  $nodes = glob($path . '/*');
  foreach ($nodes as $node) {
    if (is_dir($node)) {
      $zip->addDir($zip, $node);
    } else if (is_file($node)) {
      $zip->addFile($node);
    }
  }
}